package com.wuxb.util.disruptor;

import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class DisruptorUtil {

    public synchronized <T> void execute(Class<T> clazz) throws Exception {

            ExecutorService threadPool=null;
            Disruptor<T> disruptor=null;
            T t = clazz.newInstance();
            threadPool = Executors.newFixedThreadPool(8);
            int ringBufferSize = 1024;

            disruptor = new Disruptor<T>(new EventFactory<T>() {
                @Override
                public T newInstance() {
                    return t;
                }
            }, ringBufferSize, threadPool, ProducerType.SINGLE, new BusySpinWaitStrategy());
            doPattern(disruptor);
            disruptor.start();//启动
            CountDownLatch latch=new CountDownLatch(1);
            doProduct(disruptor,threadPool,latch);
            latch.await();
            disruptor.shutdown();
            threadPool.shutdown();
    }

    public abstract void doPattern(Disruptor disruptor);

    public  abstract void doProduct(Disruptor disruptor,ExecutorService threadPool,CountDownLatch latch);


}
